import {
	pushRequestTask,
	requestCancel,
	filterFinishedRequest,
	allRequestCancel
} from "./httpCancel.js";
import {
	ENV_URL
} from '@/utils/env.js'

function _setRequestConfig(urlConfig, params, option) {
	const {
		// 路径
		url,
		// 请求方法
		method,
		// 接口类型
	} = urlConfig;
	const token = uni.getStorageSync('token')
	let config = {
		// 环境变量
		url: ENV_URL() + url,
		method,
		data: params,
		header: {
			"admin-id": "xxxx",
			"admin-role": "xxxx",
			"user-id": "xxx",
			"user-role": "xxx",
			"Content-Type": option.type || "application/json",
			Authorization: token ? "Bearer " + token : ""
		},
		// 十五秒超时
		timeout: 15000,
	};
	if (option.responseType) {
		config.responseType = option.responseType
	}
	return config;
}
// 删除空值的字段
function deleteNullKey(obj) {
	let newObj = obj;
	for (let key in newObj) {
		if (typeof newObj[key] !== "number" && !newObj[key]) {
			delete newObj[key];
		}
	}
	return newObj;
}

function requestCatchMessage(err) {
	const translateString = (string) => {
		if (string.includes("timeout")) {
			return "服务器繁忙，请稍后再试";
		}
		return string || "请求失败";
	};
	const errMessage = err.message || "";
	const errCode = err.code || "";
	if (getValueType(errMessage) === "Object") {
		const {
			errMsg
		} = errMessage;
		return translateString(errMsg);

		// 调用reject结束
	}
	return translateString(errMessage);
}

function request(urlConfig, params, option = {}) {
	let config = _setRequestConfig(urlConfig, params, option);
	requestCancel(config.url, option);
	return new Promise((resolve, reject) => {
		console.log("请求开始", JSON.stringify(config));
		
		// 对符合条件的发起请求前拦截
		const wxRequest = uni.request({
			...config,
			success: (res) => {
				filterFinishedRequest(config.url);
				if (config.responseType === 'arraybuffer') {
					resolve({
						code: 200,
						message: null,
						data: res.data
					});
				}
				const {
					code,
					data,
					message = ""
				} = res.data;
				
				console.log("请求结束", JSON.stringify(res.data));

				// 没有权限或者token过期重新跳转到登录页
				//
				if (code === 401 || code === 7001) {
					allRequestCancel()
					reLaunchToLoginPage();
					return;
				}

				// 不是200捕获错误
				if (code !== 200) {
					reject({
						message: message ? message : "服务器异常",
						code,
					});
				} else {
					// 解决数据
					resolve(res.data);
				}

			},
			fail: (err) => {
				reject({
					message: err,
				});
			},
		});
		pushRequestTask(config.url, wxRequest);
		return wxRequest;
	}).catch((err) => {
		// 请求完成后的错误捕获
		// err为一个对象包含Msg以及code
		uni.hideLoading();

		let errString = requestCatchMessage(err);
		if (!option.isNotNeedMsg && !errString.includes("abort")) {
			uni.showToast({
				title: errString,
				duration: 2000,
				icon: "none",
			});
		}
		return Promise.reject(errString);
	});
}
export default {
	get: (url, params, option = {}) => request({
		url,
		method: 'get'
	}, params, option),
	post: (url, params, option = {}) => request({
		url,
		method: 'post'
	}, params, option),
	download: (url, params = {
		suffix: 'png'
	}) => {
		return new Promise((resolve, reject) => {
			const suffixName = url.split('.')[1] || params.suffix;
			uni.downloadFile({
				header: {
					"x-token": uni.getStorageSync('token'),
				},
				filePath: wx.env.USER_DATA_PATH + '/' + '下载.' + suffixName,
				url: url.includes('http') ? url :  setImageUrl(url),
				success: (res) => {
					if (res.statusCode === 401) {
						allRequestCancel()
						reLaunchToLoginPage();
						return;
					}
					resolve(res)
				},
				fail: () => {

					reject('保存失败')
				}
			})


		})
	}
};